<?php

namespace app\api\model;

use think\Db;
use think\Model;

/**
 *
 */
class AuctionOrder extends Model
{

    // 表名
    protected $name = 'auction_order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'createtime_text'
    ];

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['createtime'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    //尾款回调
    public function finalnotify($out_trade_no)
    {
        $order = AuctionOrder::get(['final_order_no' => $out_trade_no]);
        if ($order->final_pay_status==0){
            $order->final_pay_status = 1;
            $order->final_pay_time = time();
            $order->order_status = 3;
            $order->order_status_name = '已获拍';
            $order->save();
        }
        return true;
    }

    //押金回调
    public function notify($out_trade_no)
    {
        $order = AuctionOrder::get(['order_no' => $out_trade_no]);
        if ($order->pay_status==0){
            $order->pay_status = 1;
            $order->pay_time = time();
            $order->setAttr('order_status',1);
            $order->order_status_name = '参拍中';
            $order->save();
        }
        return true;
    }


    public function lists($user_id,$order_status)
    {

        $where = ['o.user_id'=>$user_id];

        if ($order_status!='all'){
            $where['order_status'] = $order_status;
        }

        $auction_model = new Auction();

        $status_list = $auction_model->getStatusList();

        $list = AuctionOrder::alias('o')
            ->join('auction a', 'a.auction_id=o.auction_id')
            ->where($where)
            ->field('o.order_id,o.auction_id,o.auction_name,o.auction_image,o.order_no,o.price,o.order_status,
            o.order_status_name,o.createtime,o.final_order_no,a.start_time,a.end_time,a.bid_count,a.status')
            ->order('createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        foreach ($list as $k=>$v){
            $list[$k]['start_time_text'] =  date("Y-m-d H:i:s", $v['start_time']);
            $list[$k]['end_time_text'] =  date("Y-m-d H:i:s", $v['end_time']);
            $list[$k]['status_text'] =  $status_list[$v['status']];
        }

        return $list;

    }

}
